#include <camera.h>




QMatrix4x4 Camera::getViewMat()
{
    QMatrix4x4 view;
    view.lookAt(cameraPos, cameraPos+cameraDirection, cameraUp);
    return view;
}


void Camera::DealKeyInput(CameraMovement direction){
    GLfloat velocity = movementSpeed;
    QVector3D dir = cameraDirection;
    switch(direction) {
    case FORWARD:
        dir = cameraDirection;
        break;
    case BACKWARD:
        dir = -cameraDirection;
        break;
    case LEFT:
        dir = -cameraRight;
        break;
    case RIGHT:
        dir = cameraRight;
        break;
    case UP:
        dir = {0,1,0};
        break;
    case DOWN:
        dir = {0,-1,0};
        break;
    }

    cameraPos += dir *velocity;
}

void Camera::DealMouseScroll(GLfloat Yoffset) {
    zoom-=Yoffset;
    if(zoom>45.0f)zoom = 45.0f;
    if(zoom<1.0f)zoom=1.0f;
}

void Camera::DealMouseMovement(GLfloat Xoffset, GLfloat Yoffset){
    yaw+=Xoffset*sensitivity;
    pitch+=Yoffset*sensitivity;

    if(pitch>89.0f)pitch=89.0f;
    if(pitch<-89.0f)pitch=-89.0f;

    UpdateCameraLookatMatVectors();
}

void Camera::DealKeyboardInputs() {
    if(keys[Qt::Key_W])DealKeyInput(FORWARD);
    if(keys[Qt::Key_S])DealKeyInput(BACKWARD);
    if(keys[Qt::Key_A])DealKeyInput(LEFT);
    if(keys[Qt::Key_D])DealKeyInput(RIGHT);
    if(keys[Qt::Key_E])DealKeyInput(UP);
    if(keys[Qt::Key_Q])DealKeyInput(DOWN);
}

void Camera::UpdateCameraLookatMatVectors()
{
    // cameraDirection.setX(cos(yaw)*cos(pitch));
    // cameraDirection.setY(sin(pitch));
    // cameraDirection.setZ(sin(yaw)*cos(pitch));
    QVector3D Direction(cos(yaw)*cos(pitch),sin(pitch), sin(yaw)*cos(pitch));
    cameraDirection = Direction.normalized();
    cameraRight = QVector3D::crossProduct(cameraDirection, {0,1,0}).normalized();
    cameraUp = QVector3D::crossProduct(cameraRight, cameraDirection);
}
